package com.biglead.demo.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.OutputStream;

@Slf4j
public class JsonUtils {

    public static void toJson(OutputStream outputStream, Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            mapper.writeValue(outputStream, obj);
        } catch (IOException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    }

    public static String toJson(Object obj) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            log.error("序列化失败：{}", e.getMessage());
            return null;
        }
    }

    public static <T> T toObj (String obj, Class<T> clazz) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(obj.getBytes("UTF-8"), clazz);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("反序列化失败: {}", e.getMessage());

        }
        return null;
    }

}
